import serial
import serial.tools.list_ports
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QThread
from utils.logger import logger

class SerialDriver(QObject):
    data_received = pyqtSignal(bytes)
    connection_status = pyqtSignal(bool)
    def __init__(self, parent=None):
        super().__init__()
        self.serial_port = None
        self.read_thread = None
        self.runninng = False
    def list_ports(self):
        return [port.device for port in serial.tools.list_ports.comports()]
    def open(self, port, baudrate=115200, timeout=1):
        try:
            self.serial_port = serial.Serial(
                port=port,
                baudrate=baudrate,
                timeout=timeout,
                write_timeout=timeout
            )
            self.runninng = True
            self.read_thread = QThread()
            self.read_thread.run = self._read_data
            self.read_thread.start()
            self.connection_status.emit(True)
            return True
        except Exception as e:
            self.connection_status.emit(False)
            return False
    def close(self):
        self.runninng = False
        if self.read_thread and self.read_thread.isRunning():
            self.read_thread.quit()
            self.read_thread.wait()
        if self.serial_port and self.serial_port.is_open:
            self.serial_port.close()
        self.connection_status.emit(False)
    def write(self, data):
        if self.serial_port and self.serial_port.is_open:
            try:
                self.serial_port.write(data)
                return len(data)
            except Exception as e:
                return 0
        return 0
    def _read_data(self):
        while self.runninng and self.serial_port and self.serial_port.is_open:
            try:
                if self.serial_port.in_waiting:
                    data = self.serial_port.read(self.serial_port.in_waiting)
                    self.data_received.emit(data)
            except Exception as e:
                # 记录异常信息，但不立即断开连接
                logger.error(f"读取串口数据时出错: {e}")